package com.mb.cart.service;

import com.mb.cart.mapper.CartMapper;
import com.mb.common.pojo.Cart;
import com.mb.common.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
@Service
public class CartService {

    @Autowired(required = false)
    private CartMapper cartMapper;

    @Autowired
    private RestTemplate restTemplate;

    public List<Cart> queryMyCarts(String userId) {
        return cartMapper.selectId(userId);
    }

    public void addCart(Cart cart) {
        /*
        * 1.查询新增购物车是否存在
        * 2.不存在 —— 新增
        * 3.存  在 —— 更新数据
        * */
        Cart exit = cartMapper.selectUserIdAndProductId(cart);

        if(exit==null){
            //为空 则补齐对象  写入数据库
//            String url="http://productservice/product/manage/item/"+cart.getProductId();
//            Product product = restTemplate.getForObject(url, Product.class);

            Product product = cartMapper.selectProductById(cart.getProductId());

            cart.setProductName(product.getProductName());
            cart.setProductPrice(product.getProductPrice());
            cart.setProductImage(product.getProductImgurl());
            //将insert写入数据库
            cartMapper.insertCart(cart);
        }else {
            //不为空查到了这个商品
            int num = cart.getNum();
            int oldnum = exit.getNum();
            cart.setNum(num+oldnum);
            cartMapper.updateNum(cart);
        }
    }

    public void gxCartNum(Cart cart) {
        cartMapper.updateNumCart(cart);
    }

    public void delCart(Cart cart) {
        cartMapper.delCart(cart);
    }
}
